﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using devtm.Collections;
using devtm.Editor.Configuration.Command;
using devtm.Editor.Configuration.ConfigurationProperties;
using devtm.Editor.Configuration.Merge;
using devtm.Editor.Configuration.Messages;
using devtm.Helpers;
using devtm.Types;
using devtm.Types.LazyLoading;
using System.Xml.Linq;
using System.Reflection;
using devtm.Helpers.Factories;

namespace devtm.Editor.Configuration
{


    public static class Datas
    {

        public static event PropertyChangedEventHandler PropertyChanged;

        #region File
       

        private static FileInfo _file;
        public static FileInfo FileConfiguration { get { return _file; } }
        public static ConfigurationFileSourceWatcher Watcher;


        public static bool OpenConfiguration(string filename)
        {

            Datas.SaveOptions();

            if (_file != null)
            {

                if (Datas.IsModified)
                    if (MessageBox.Show(Properties.Resources.DoYouWantSaveYourModifications,
                        Properties.Resources.Save,
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Warning,
                        MessageBoxResult.Yes) == MessageBoxResult.Yes)
                        SaveConfiguration();

                DirectoriesSearch.Clear();

            }

            _fusion = false;
            _forceSave = true;
            _configurationMode = ConfigurationSaveMode.Modified;
            //SaveAs = false;

            _file = new FileInfo(filename);

            if (!_file.Exists)
                throw new Exception(Properties.Resources.FileNotFound);


            var pp = Datas.ConfigurationsProperties;

            GetRegisterDirectoryForFileName(_file.Directory);

            if (!Datas.ConfigurationsProperties.ContainsKey(_file.FullName))
                Datas.ConfigurationsProperties.Add(new ConfigurationsPropertiesSettings() { Filename = _file.FullName });


            Datas.Lazy = new devtm.Types.LazyLoading.LazyLoadingHelper(Datas.DirectoriesSearch, Datas.lazy_ErrorsEvent);

            if (TryLoad(filename))
            {
                Datas.LastError = null;

                Watcher =
                    new ConfigurationFileSourceWatcher(_file);

                ListeChange.Clear();
                PropertyChange("File");

                return true;

            }

            return false;

        }

        private static bool TryLoad(string filename)
        {
            var ii = new ExeConfigurationFileMap() { ExeConfigFilename = filename };

            // The 'mangas.audit' start tag on line 30 position 6 does not match the end tag of 'configuration
            // "The 'configuration' start tag on line 2 position 2 does not match the end tag of 'mangas.audit'. Line 34, position 7

            try
            {
                Configuration = ConfigurationManager.OpenMappedExeConfiguration(ii, ConfigurationUserLevel.None);
                return true;
            }
            catch (Exception ex)
            {
                Datas.LastError = new Exception("Wrong format configuration file.\n\n" + ex.Message, ex);
                return false;
            }
            
        }


        public static void LoadTypes(IEnumerable<DirectoryInfo> list)
        {

            Datas.jobs.Add(() => Datas.ListeAssemblies.Initialize());

            if (list != null)
                foreach (DirectoryInfo dir in list)
                    Datas.ListeAssemblies.AddDirectorySearch(dir);

            Datas.jobs.Add(() => Datas.ListeAssemblies.LoadTypes());

            Datas.jobs.Start(true);

        }


        public static void SaveConfiguration()
        {
            SaveConfiguration(_fusion, _configurationMode, _forceSave);
        }

        //private static bool SaveAs;
        private static bool _fusion;
        private static bool _forceSave;
        private static ConfigurationSaveMode _configurationMode;
        public static void SaveConfiguration(bool fusion, ConfigurationSaveMode configurationMode, bool forceSave)
        {

            _fusion = fusion;
            _forceSave = forceSave;
            _configurationMode = configurationMode;

            try
            {

                Datas.SaveOptions();

                _file.Attributes = FileAttributes.Normal;

                Configuration.Save(configurationMode, forceSave);

                Watcher.lastWriteTime = File.GetLastWriteTime(_file.FullName);

                ListeChange.Clear();
                _listForceSave.Clear();

                
                DeleteUpdate();
                PropertyChange("IsModified");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error on save." + _file.Name + "\n\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                
            }
            

        }

        public static void SaveOptions()
        {
            
            string filename = Environment.CurrentDirectory + @"\config.xml";
            
            Datas.ConfigurationsProperties.SaveXml(filename);

        }

        public static void LoadOptions()
        {

            RecentFiles = new ConfigurationProperties.RecentFiles();
            string filename = Environment.CurrentDirectory + @"\config.xml";
            if (!File.Exists(filename))
                return;

            Datas.ConfigurationsProperties.CollectionChanged += ConfigurationsProperties_CollectionChanged;

            Datas.ConfigurationsProperties = Datas.ConfigurationsProperties.LoadXml(filename);

            foreach (var item in Datas.ConfigurationsProperties)
                if (File.Exists(item.Filename))
                    RecentFiles.Add(new RecentFile() { FullName = item.Filename });
            
            foreach (var item in Datas.ConfigurationsProperties.Directories)
            {
                if (Datas.DirectoriesSearch.ContainsKey(item))
                    return;

                DirectoryInfo d = new DirectoryInfo(item);

                Datas.DirectoriesSearch.Add(d);
            }

        }

        static void ConfigurationsProperties_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            //RecentFiles.Add(item.Filename);
        }

        public static RecentFiles RecentFiles { get; set; }

                 


       

        private static void GetRegisterDirectoryForFileName(DirectoryInfo dir)
        {


            Datas.DirectoriesSearch.Clear();

            AddDirectoryLibrary(dir);

            if (_file != null)
            {

                if (!Datas.ConfigurationsProperties.ContainsKey(_file.FullName))
                    Datas.ConfigurationsProperties.Add(
                        new ConfigurationsPropertiesSettings() { Filename = _file.FullName });


                foreach (var item in Datas.ConfigurationsProperties[_file.FullName].Directories)
                {
                    if (Datas.DirectoriesSearch.ContainsKey(item))
                        return;

                    DirectoryInfo d = new DirectoryInfo(item);
                    Datas.DirectoriesSearch.Add(d);
                }

            }
        }


        private static void LoadRecentFiles()
        {

            string filename = Environment.CurrentDirectory + @"\RecentFiles.xml";
            if (!File.Exists(filename))
                return;

            Datas.ConfigurationsProperties = Datas.ConfigurationsProperties.LoadXml(filename);

            foreach (var item in Datas.ConfigurationsProperties.Directories)
            {
                if (Datas.DirectoriesSearch.ContainsKey(item))
                    return;

                DirectoryInfo d = new DirectoryInfo(item);

                Datas.DirectoriesSearch.Add(d);
            }

            if (_file != null)
                if (!Datas.ConfigurationsProperties.ContainsKey(_file.FullName))
                    Datas.ConfigurationsProperties.Add(
                        new ConfigurationsPropertiesSettings() { Filename = _file.FullName });


            foreach (var item in Datas.ConfigurationsProperties[_file.FullName].Directories)
            {
                if (Datas.DirectoriesSearch.ContainsKey(item))
                    return;

                DirectoryInfo d = new DirectoryInfo(item);
                Datas.DirectoriesSearch.Add(d);
            }

        }

        /// <summary>
        /// Closes the configuration file
        /// </summary>
        public static void CloseConfiguration()
        {

            if (Datas.IsModified)
                if (MessageBox.Show(Properties.Resources.DoYouWantSaveYourModifications, Properties.Resources.Save, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                    SaveConfiguration();

            jobs.Close = true;

            if (Watcher != null)
                Watcher.quit = true;
        }

        public static System.Configuration.Configuration Configuration { get; private set; }

        private static bool _isModified;
        public static bool IsModified
        {
            get
            {
                if (ListeChange.ListeUndo.Count != 0)
                    return true;

                if (_listForceSave.Count != 0)
                    return true;

                return _isModified;
            }
            set
            {
                if (_isModified == value)
                    return;

                _isModified = value;

                PropertyChange("IsModified");
            }
        }

        #region Pattern command
        

        public static CommandManager ListeChange = new CommandManager();


        public static void ClearUpdate()
        {

            IsModified = false;
        }

        public static void DeleteUpdate()
        {

            IsModified = false;
        }

        #endregion

        private static void PropertyChange(string propertyName)
        {

            if (PropertyChanged != null)
                PropertyChanged(null, new PropertyChangedEventArgs(propertyName));

        }

        #endregion

        #region Directories

        public static ListeAssemblies ListeAssemblies { get; set; }
        public static TableCollection<DirectoryInfo, string> DirectoriesSearch;
        public static ConfigurationsPropertiesCollection ConfigurationsProperties;

        public static void AddDirectoryLibrary(DirectoryInfo path)
        {
            if (!path.Exists)
                throw new Exception(String.Format(CultureInfo.CurrentCulture, Properties.Resources.ThePathExist0, path.FullName));

            if (!DirectoriesSearch.ContainsKey(path.FullName))
                DirectoriesSearch.Add(path);
        }

        public static void AddDirectoryLibrary(string path)
        {
            AddDirectoryLibrary(new DirectoryInfo(path));
        }

        internal static void ClearDirectoriesLibrairies()
        {
            if (DirectoriesSearch != null)
                DirectoriesSearch.Clear();
        }


        internal static bool ShowNode(ConfigurationElement element)
        {
            if (element == null || element is DefaultSection || element is IgnoreSection)
                return false;

            if (element is System.Configuration.ProtectedConfigurationSection || element is ConnectionStringsSection || element is ConnectionStringSettingsCollection || element is System.Configuration.KeyValueConfigurationCollection || element is System.Configuration.AppSettingsSection)
                return true;
            //if (element.ElementInformation.IsPresent)

            if (element is ConfigurationSection)
            {
                var i = (element as ConfigurationSection).SectionInformation;
                if (!i.IsDeclared)
                    return false;

            }

            if (element.ElementInformation.IsPresent)
                return true;



            return true;
        }
        internal static bool ShowNode(ConfigurationSectionGroup sectiongroup)
        {

            if (!sectiongroup.IsDeclared)
                return false;

            return true;
        }


        public static System.Xml.Linq.XElement Xml { get; set; }

        public static Jober jobs = new Jober();

        public static LazyLoadingHelper Lazy;

        public static Hashtable Images;
        #endregion

        #region Erreurs

        public static void NotifyError(string key, Exception ex)
        {

            MessageTextError msg = new MessageTextError(
                Datas.Messages,
                ex.Message,
                TypeMessage.Error)
            {
                Label = Properties.Resources.Close,
                Line = 0
            };

            msg.Action = () => msg.List.Remove(msg);

            Datas.Messages.Add(msg);
        }


        public static void NotifyError(MemberInfo prop, Exception ex)
        {

            MessageTextError msg = new MessageTextError(
                Datas.Messages,
                ex.Message,
                TypeMessage.Error)
            {
                Label = Properties.Resources.Close,
                Line = 0
            };

            msg.Action = () => msg.List.Remove(msg);

            Datas.Messages.Add(msg);

        }

    

        public static void lazy_ErrorsEvent(object sender, System.IO.ErrorEventArgs e)
        {
            throw new NotImplementedException();
        }


        public static void TraitementError(String key, ConfigurationErrorsException e1)
        {
            foreach (var item in e1.Errors)
            {


                String msg = ((System.Configuration.ConfigurationErrorsException)(item)).BareMessage;

                List<String> lst = new List<String>();
                foreach (Match Mitem in Regex.Matches(msg, @"'[a-zA-Z09\.]*'"))
                    lst.Add(Mitem.Value);

                if (lst.Count() == 2)
                {
                    String TypeName = lst[0];
                    FileInfo FileName = new FileInfo(Datas.FileConfiguration.Directory.FullName + @"\" + lst[1] + ".dll");
                    if (!FileName.Exists)
                    {
                        // la dll n'existe pas.
                        //frmAction.Liste.Add(
                        //    new Actions.DefaultAction()
                        //    {
                        //        Required = true,
                        //        Description = String.Format(CultureInfo.CurrentCulture, "the section name '{0}' can t be loaded. the file {1} is missing.", key, FileName.FullName),
                        //        Btn1 = " Remove this section",
                        //        Action1 = () => DelSection(null, null, key),
                        //        ViewBtn1 = System.Windows.Visibility.Visible,
                        //        Btn2 = " Pass",
                        //        ViewBtn2 = System.Windows.Visibility.Visible,
                        //    }
                        //);
                    }
                    else
                    {
                        //frmAction.Liste.Add(
                        //new Actions.DefaultAction()
                        //{
                        //    Required = true,
                        //    Description = String.Format(CultureInfo.CurrentCulture, "the section name '{0}' can t be loaded. \n the type {1} is not present in {2}", key, lst[0], lst[1]),
                        //    Btn1 = " Remove this section",
                        //    Action1 = () => DelSection(null, null, key),
                        //    ViewBtn1 = System.Windows.Visibility.Visible,
                        //    Btn2 = " Pass",
                        //    ViewBtn2 = System.Windows.Visibility.Visible,
                        //}
                        //);
                    }
                }
                else
                {
                    //frmAction.Liste.Add(
                    //    new Actions.DefaultAction()
                    //    {
                    //        Required = true,
                    //        Description = String.Format(CultureInfo.CurrentCulture, "the section name '{0}' can t be loaded. \n {1}", key, msg),
                    //        Btn1 = " Remove this section",
                    //        Action1 = () => DelSection(null, null, key),
                    //        ViewBtn1 = System.Windows.Visibility.Visible,
                    //        Btn2 = " Pass",
                    //        ViewBtn2 = System.Windows.Visibility.Visible,
                    //    }
                    //);
                }


            }
            return;
        }
        #endregion


        static Datas()
        {

            devtm.Editor.Configuration.Templates.DictionaryTemplate.Init();

            Images = new Hashtable();

            #region Add

            Images.Add("connectionStrings", "connexionString.png");
            Images.Add("system.transactions", "system.transaction.png");
            Images.Add("system.net", "system.net.png");
            Images.Add("system.web", "system.web.png");
            Images.Add("caching", "caching.png");
            //Images.Add("ConnectionStrings", "");
            //Images.Add("LocalSqlServer", "");
            Images.Add("appSettings", "setting.png");
            //Images.Add("Settings", "");
            Images.Add("configProtectedData", "la-protection-bouclier-icone-4586-32.png");
            //Images.Add("Providers", "");
            //Images.Add("RsaProtectedConfigurationProvider", "");
            //Images.Add("DataProtectionConfigurationProvider", "");
            //Images.Add("uri", "");
            //Images.Add("Idn", "");
            //Images.Add("IriParsing", "");
            //Images.Add("SchemeSettings", "");
            //Images.Add("system.windows.forms", "");
            Images.Add("system.diagnostics", "diagnostiques.png");
            //Images.Add("Assert", "");
            Images.Add("PerfCounters", "Compteur.png");
            //Images.Add("Sources", "");
            //Images.Add("SharedListeners", "");
            //Images.Add("Switches", "");
            Images.Add("Trace", "loupe.png");
            Images.Add("mailSettings", "smtp.png");
            //Images.Add("Listeners", "");
            //Images.Add("Default", "");
            //Images.Add("Filter", "");
            //Images.Add("machineSettings", "");
            //Images.Add("defaultSettings", "");
            //Images.Add("smtp", "");
            //Images.Add("Network", "");
            //Images.Add("SpecifiedPickupDirectory", "");
            //Images.Add("connectionManagement", "");
            //Images.Add("ConnectionManagement", "");
            //Images.Add("webRequestModules", "");
            //Images.Add("WebRequestModules", "");
            //Images.Add("WebRequestModuleElementCollection", "");
            //Images.Add("WebRequestModuleElementCollection", "");
            //Images.Add("WebRequestModuleElementCollection", "");
            //Images.Add("WebRequestModuleElementCollection", "");
            //Images.Add("settings", "");
            //Images.Add("HttpWebRequest", "");
            //Images.Add("Ipv6", "");
            //Images.Add("ServicePointManager", "");
            //Images.Add("Socket", "");
            //Images.Add("WebProxyScript", "");
            //Images.Add("PerformanceCounters", "");
            //Images.Add("HttpListener", "");
            //Images.Add("authenticationModules", "");
            //Images.Add("AuthenticationModules", "");
            //Images.Add("AuthenticationModuleElementCollection", "");
            //Images.Add("AuthenticationModuleElementCollection", "");
            //Images.Add("AuthenticationModuleElementCollection", "");
            //Images.Add("AuthenticationModuleElementCollection", "");
            //Images.Add("AuthenticationModuleElementCollection", "");
            //Images.Add("defaultProxy", "");
            //Images.Add("BypassList", "");
            //Images.Add("Module", "");
            //Images.Add("Proxy", "");
            //Images.Add("requestCaching", "");
            //Images.Add("DefaultHttpCachePolicy", "");
            //Images.Add("DefaultFtpCachePolicy", "");
            //Images.Add("outputCache", "");
            //Images.Add("Providers", "");
            //Images.Add("outputCacheSettings", "");
            //Images.Add("OutputCacheProfiles", "");
            //Images.Add("sqlCacheDependency", "");
            //Images.Add("Databases", "");
            //Images.Add("cache", "");
            //Images.Add("webParts", "");
            //Images.Add("Personalization", "");
            //Images.Add("Authorization", "");
            //Images.Add("Rules", "");
            //Images.Add("Providers", "");
            //Images.Add("Transformers", "");
            //Images.Add("httpHandlers", "");
            //Images.Add("Handlers", "");
            //Images.Add("clientTarget", "");
            //Images.Add("ClientTargets", "");
            Images.Add("profile", "profile.png");
            //Images.Add("Providers", "");
            //Images.Add("AspNetSqlProfileProvider", "");
            //Images.Add("PropertySettings", "");
            //Images.Add("sessionState", "");
            //Images.Add("Providers", "");
            //Images.Add("httpRuntime", "");
            Images.Add("globalization", "globalization.png");
            //Images.Add("urlMappings", "");
            //Images.Add("UrlMappings", "");
            //Images.Add("partialTrustVisibleAssemblies", "");
            //Images.Add("PartialTrustVisibleAssemblies", "");
            //Images.Add("securityPolicy", "");
            //Images.Add("TrustLevels", "");
            //Images.Add("trust", "");
            //Images.Add("deviceFilters", "");
            //Images.Add("Filters", "");
            //Images.Add("anonymousIdentification", "");
            Images.Add("authentication", "authentifiant-icone-6882-32.png");
            //Images.Add("Forms", "");
            //Images.Add("Credentials", "");
            //Images.Add("Users", "");
            //Images.Add("Passport", "");
            //Images.Add("healthMonitoring", "");
            //Images.Add("BufferModes", "");
            //Images.Add("Providers", "");
            Images.Add("Profiles", "profile.png");
            //Images.Add("Rules", "");
            //Images.Add("EventMappings", "");
            Images.Add("siteMap", "sitemap.png");
            //Images.Add("Providers", "");
            Images.Add("membership", "Membership.png");
            //Images.Add("Providers", "");
            //Images.Add("AspNetSqlMembershipProvider", "");
            Images.Add("customErrors", "erreur.png");
            //Images.Add("Errors", "");
            //Images.Add("xhtmlConformance", "");
            //Images.Add("pages", "");
            //Images.Add("Namespaces", "");
            //Images.Add("Controls", "");
            //Images.Add("TagMapping", "");
            //Images.Add("IgnoreDeviceFilters", "");
            //Images.Add("webControls", "");
            //Images.Add("hostingEnvironment", "");
            //Images.Add("compilation", "");
            //Images.Add("Compilers", "");
            //Images.Add("Assemblies", "");
            //Images.Add("BuildProviders", "");
            //Images.Add("FolderLevelBuildProviders", "");
            //Images.Add("ExpressionBuilders", "");
            //Images.Add("CodeSubDirectories", "");
            //Images.Add("httpModules", "");
            //Images.Add("Modules", "");
            Images.Add("roleManager", "roles.png");
            //Images.Add("Providers", "");
            //Images.Add("AspNetSqlRoleProvider", "");
            //Images.Add("AspNetWindowsTokenRoleProvider", "");
            //Images.Add("processModel", "");
            //Images.Add("protocols", "");
            //Images.Add("Protocols", "");
            //Images.Add("machineKey", "");
            //Images.Add("httpCookies", "");
            //Images.Add("authorization", "");
            //Images.Add("Rules", "");
            //Images.Add("trace", "");
            //Images.Add("deployment", "");
            //Images.Add("mobileControls", "");
            //Images.Add("Devices", "");
            //Images.Add("identity", "");
            //Images.Add("webServices", "");
            //Images.Add("ConformanceWarnings", "");
            //Images.Add("BasicProfile1_1", "");
            //Images.Add("Current", "");
            //Images.Add("ConformanceWarnings", "");
            //Images.Add("ConformanceWarnings", "");
            //Images.Add("Current", "");
            //Images.Add("Protocols", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("Protocols", "");
            //Images.Add("HttpSoap12", "");
            //Images.Add("HttpSoap", "");
            //Images.Add("HttpPostLocalhost", "");
            //Images.Add("Documentation", "");
            //Images.Add("SoapEnvelopeProcessing", "");
            //Images.Add("Diagnostics", "");
            //Images.Add("ServiceDescriptionFormatExtensionTypes", "");
            //Images.Add("SoapExtensionImporterTypes", "");
            //Images.Add("SoapExtensionReflectorTypes", "");
            //Images.Add("SoapExtensionTypes", "");
            //Images.Add("SoapServerProtocolFactoryType", "");
            //Images.Add("SoapTransportImporterTypes", "");
            //Images.Add("WsdlHelpGenerator", "");
            //Images.Add("fullTrustAssemblies", "");
            //Images.Add("FullTrustAssemblies", "");
            //Images.Add("sessionPageState", "");
            //Images.Add("memoryCache", "");
            //Images.Add("NamedCaches", "");
            //Images.Add("dataContractSerializer", "");
            //Images.Add("DeclaredTypes", "");
            //Images.Add("xmlSerializer", "");
            //Images.Add("dateTimeSerialization", "");
            //Images.Add("schemaImporterExtensions", "");
            //Images.Add("SchemaImporterExtensions", "");
            //Images.Add("SqlTypesSchemaImporterChar", "");
            //Images.Add("SqlTypesSchemaImporterNChar", "");
            //Images.Add("SqlTypesSchemaImporterVarChar", "");
            //Images.Add("SqlTypesSchemaImporterNVarChar", "");
            //Images.Add("SqlTypesSchemaImporterText", "");
            //Images.Add("SqlTypesSchemaImporterNText", "");
            //Images.Add("SqlTypesSchemaImporterVarBinary", "");
            //Images.Add("SqlTypesSchemaImporterBinary", "");
            //Images.Add("SqlTypesSchemaImporterImage", "");
            //Images.Add("SqlTypesSchemaImporterDecimal", "");
            //Images.Add("SqlTypesSchemaImporterNumeric", "");
            //Images.Add("SqlTypesSchemaImporterBigInt", "");
            //Images.Add("SqlTypesSchemaImporterInt", "");
            //Images.Add("SqlTypesSchemaImporterSmallInt", "");
            //Images.Add("SqlTypesSchemaImporterTinyInt", "");
            //Images.Add("SqlTypesSchemaImporterBit", "");
            //Images.Add("SqlTypesSchemaImporterFloat", "");
            //Images.Add("SqlTypesSchemaImporterReal", "");
            //Images.Add("SqlTypesSchemaImporterDateTime", "");
            //Images.Add("SqlTypesSchemaImporterSmallDateTime", "");
            //Images.Add("SqlTypesSchemaImporterMoney", "");
            //Images.Add("SqlTypesSchemaImporterSmallMoney", "");
            //Images.Add("SqlTypesSchemaImporterUniqueIdentifier", "");
            //Images.Add("httpHandlers", "");
            //Images.Add("Handlers", "");
            //Images.Add("net.pipe", "");
            //Images.Add("AllowAccounts", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("diagnostics", "");
            //Images.Add("net.tcp", "");
            //Images.Add("AllowAccounts", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("SecurityIdentifierElementCollection", "");
            //Images.Add("tracking", "");
            //Images.Add("Profiles", "");
            //Images.Add("Workflows", "");
            //Images.Add("ProfileWorkflowElementCollection", "");
            //Images.Add("WorkflowInstanceQueries", "");
            //Images.Add("WorkflowInstanceQueryElementCollection", "");
            //Images.Add("States", "");
            //Images.Add("Annotations", "");
            //Images.Add("ActivityStateQueries", "");
            //Images.Add("ActivityStateQueryElementCollection", "");
            //Images.Add("States", "");
            //Images.Add("Variables", "");
            //Images.Add("Arguments", "");
            //Images.Add("Annotations", "");
            //Images.Add("ActivityScheduledQueries", "");
            //Images.Add("CancelRequestedQueries", "");
            //Images.Add("FaultPropagationQueries", "");
            //Images.Add("FaultPropagationQueryElementCollection", "");
            //Images.Add("Annotations", "");
            //Images.Add("BookmarkResumptionQueries", "");
            //Images.Add("CustomTrackingQueries", "");
            //Images.Add("routing", "");
            //Images.Add("Filters", "");
            //Images.Add("FilterTables", "");
            //Images.Add("BackupLists", "");
            //Images.Add("NamespaceTable", "");
            //Images.Add("services", "");
            //Images.Add("Services", "");
            //Images.Add("extensions", "");
            //Images.Add("BehaviorExtensions", "");
            //Images.Add("clientCredentials", "");
            //Images.Add("serviceCredentials", "");
            //Images.Add("callbackDebug", "");
            //Images.Add("clientVia", "");
            //Images.Add("synchronousReceive", "");
            //Images.Add("dispatcherSynchronization", "");
            //Images.Add("serviceMetadata", "");
            //Images.Add("serviceDebug", "");
            //Images.Add("serviceAuthenticationManager", "");
            //Images.Add("serviceAuthorization", "");
            //Images.Add("serviceSecurityAudit", "");
            //Images.Add("serviceThrottling", "");
            //Images.Add("transactedBatching", "");
            //Images.Add("dataContractSerializer", "");
            //Images.Add("serviceTimeouts", "");
            //Images.Add("callbackTimeouts", "");
            //Images.Add("useRequestHeadersForMetadataAddress", "");
            //Images.Add("clear", "");
            //Images.Add("remove", "");
            //Images.Add("persistenceProvider", "");
            //Images.Add("workflowRuntime", "");
            //Images.Add("enableWebScript", "");
            //Images.Add("webHttp", "");
            //Images.Add("serviceDiscovery", "");
            //Images.Add("endpointDiscovery", "");
            //Images.Add("etwTracking", "");
            //Images.Add("routing", "");
            //Images.Add("soapProcessing", "");
            //Images.Add("workflowIdle", "");
            //Images.Add("workflowUnhandledException", "");
            //Images.Add("bufferedReceive", "");
            //Images.Add("sendMessageChannelCache", "");
            //Images.Add("sqlWorkflowInstanceStore", "");
            //Images.Add("workflowInstanceManagement", "");
            //Images.Add("Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior", "");
            //Images.Add("BindingElementExtensions", "");
            //Images.Add("binaryMessageEncoding", "");
            //Images.Add("compositeDuplex", "");
            //Images.Add("oneWay", "");
            //Images.Add("transactionFlow", "");
            //Images.Add("httpsTransport", "");
            //Images.Add("httpTransport", "");
            //Images.Add("msmqIntegration", "");
            //Images.Add("msmqTransport", "");
            //Images.Add("mtomMessageEncoding", "");
            //Images.Add("namedPipeTransport", "");
            //Images.Add("peerTransport", "");
            //Images.Add("pnrpPeerResolver", "");
            //Images.Add("privacyNoticeAt", "");
            //Images.Add("reliableSession", "");
            //Images.Add("security", "");
            //Images.Add("sslStreamSecurity", "");
            //Images.Add("tcpTransport", "");
            //Images.Add("textMessageEncoding", "");
            //Images.Add("unrecognizedPolicyAssertions", "");
            //Images.Add("useManagedPresentation", "");
            //Images.Add("windowsStreamSecurity", "");
            //Images.Add("webMessageEncoding", "");
            //Images.Add("context", "");
            //Images.Add("byteStreamMessageEncoding", "");
            //Images.Add("discoveryClient", "");
            //Images.Add("BindingExtensions", "");
            //Images.Add("basicHttpBinding", "");
            //Images.Add("customBinding", "");
            //Images.Add("msmqIntegrationBinding", "");
            //Images.Add("netMsmqBinding", "");
            //Images.Add("netNamedPipeBinding", "");
            //Images.Add("netPeerTcpBinding", "");
            //Images.Add("netTcpBinding", "");
            //Images.Add("wsDualHttpBinding", "");
            //Images.Add("wsFederationHttpBinding", "");
            //Images.Add("ws2007FederationHttpBinding", "");
            //Images.Add("wsHttpBinding", "");
            //Images.Add("ws2007HttpBinding", "");
            //Images.Add("mexHttpBinding", "");
            //Images.Add("mexHttpsBinding", "");
            //Images.Add("mexNamedPipeBinding", "");
            //Images.Add("mexTcpBinding", "");
            //Images.Add("wsHttpContextBinding", "");
            //Images.Add("netTcpContextBinding", "");
            //Images.Add("webHttpBinding", "");
            //Images.Add("basicHttpContextBinding", "");
            //Images.Add("EndpointExtensions", "");
            //Images.Add("mexEndpoint", "");
            //Images.Add("dynamicEndpoint", "");
            //Images.Add("discoveryEndpoint", "");
            //Images.Add("udpDiscoveryEndpoint", "");
            //Images.Add("announcementEndpoint", "");
            //Images.Add("udpAnnouncementEndpoint", "");
            //Images.Add("workflowControlEndpoint", "");
            //Images.Add("webHttpEndpoint", "");
            //Images.Add("webScriptEndpoint", "");
            //Images.Add("client", "");
            //Images.Add("Endpoints", "");
            //Images.Add("Metadata", "");
            //Images.Add("PolicyImporters", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("PolicyImporterElementCollection", "");
            //Images.Add("WsdlImporters", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("WsdlImporterElementCollection", "");
            //Images.Add("serviceHostingEnvironment", "");
            //Images.Add("TransportConfigurationTypes", "");
            //Images.Add("BaseAddressPrefixFilters", "");
            //Images.Add("ServiceActivations", "");
            //Images.Add("behaviors", "");
            //Images.Add("EndpointBehaviors", "");
            //Images.Add("ServiceBehaviors", "");
            //Images.Add("comContracts", "");
            //Images.Add("ComContracts", "");
            //Images.Add("bindings", "");
            //Images.Add("BasicHttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("CustomBinding", "");
            //Images.Add("MsmqIntegrationBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("NetPeerTcpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("NetMsmqBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("NetNamedPipeBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("NetTcpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("WSFederationHttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("WS2007FederationHttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("WSHttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("WS2007HttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("WSDualHttpBinding", "");
            //Images.Add("Bindings", "");
            //Images.Add("commonBehaviors", "");
            //Images.Add("EndpointBehaviors", "");
            //Images.Add("CommonEndpointBehaviorElement", "");
            //Images.Add("ServiceBehaviors", "");
            //Images.Add("CommonServiceBehaviorElement", "");
            //Images.Add("protocolMapping", "");
            //Images.Add("ProtocolMappingCollection", "");
            //Images.Add("ProtocolMappingElementCollection", "");
            //Images.Add("ProtocolMappingElementCollection", "");
            //Images.Add("ProtocolMappingElementCollection", "");
            //Images.Add("ProtocolMappingElementCollection", "");
            //Images.Add("standardEndpoints", "");
            //Images.Add("MexEndpoint", "");
            //Images.Add("Endpoints", "");
            //Images.Add("diagnostics", "");
            //Images.Add("MessageLogging", "");
            //Images.Add("Filters", "");
            //Images.Add("EndToEndTracing", "");
            //Images.Add("machineSettings", "");

            #endregion

            DirectoriesSearch = new TableCollection<DirectoryInfo, string>(c => c.FullName);
            
            ListeAssemblies = new ListeAssemblies();

            AssemblyDescription des1 = AssemblyDescription.Get(typeof(System.Configuration.ConfigurationElement).Assembly.GetName().FullName, true, true, true);
            ListeAssemblies.LoadByDefault.Add(des1);

            AssemblyDescription des2 = AssemblyDescription.Get(typeof(devtm.CommonInteractive.Config.CheckConfig).Assembly.GetName().FullName, true, true, true);
            ListeAssemblies.LoadByDefault.Add(des2);



            DirectoriesSearch.CollectionChanged += DirectoriesSearch_CollectionChanged;
            ConfigurationsProperties = new ConfigurationsPropertiesCollection();
            //Datas.Types = new devtm.Editor.Configuration.Customs.CustomTypeCollection();

            InsertGac();

        }


        
        public static void InsertGac()
        {
            GlobalAssemblyCash gac = new GlobalAssemblyCash();
            foreach (AssemblyDescription item in gac.Assemblies())
                ListeAssemblies.AddAssemblyDescription(item);
        }

        static void DirectoriesSearch_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (DirectoryInfo item in e.NewItems)
                {

                    if (FileConfiguration.Directory.FullName == item.FullName)
                        continue;

                    var _datas = Datas.ConfigurationsProperties[_file.FullName];
                    if (!_datas.Directories.Contains(item.FullName))
                    {

                        _datas.Directories.Add(item.FullName);

                        Datas.SaveOptions();

                    }

                }
            }
        }

        public static ObservableCollection<MessageText> Messages = new ObservableCollection<MessageText>();
        public static Exception LastError;

        public static ConfigurationSaveMode SaveMode { get; set; }



        #region Force save

        private static List<SectionInformation> _listForceSave = new List<SectionInformation>();
        internal static void ForceSave(SectionInformation _infos, bool value)
        {
            string name = _infos.Name;

            if (value)
            {
                if (!_listForceSave.Contains(_infos))
                    _listForceSave.Add(_infos);
            }
            else
            {
                if (_listForceSave.Contains(_infos))
                    _listForceSave.Remove(_infos);
            }

            PropertyChange("IsModified");

        }

        #endregion


        internal static void TestChange()
        {
            PropertyChange("IsModified");
        }

    }
}
